package logic

import (
	"context"
	"github.com/spf13/cast"
	"xialou_platform/services/agent/rpc/agentClient"
	"xialou_platform/services/agent/rpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type StoreChangeBindLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewStoreChangeBindLogic(ctx context.Context, svcCtx *svc.ServiceContext) *StoreChangeBindLogic {
	return &StoreChangeBindLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *StoreChangeBindLogic) StoreChangeBind(in *agentClient.StoreChangeBindReq) (*agentClient.EmptyBody, error) {
	agentId := cast.ToInt64(in.AgentId)
	_, err := l.svcCtx.AgentModel.FindOne(l.ctx, in.AgentId)
	if err != nil {
		return nil, err
	}

	store, err := l.svcCtx.StoreModel.FindOne(l.ctx, in.StoreId)
	if err != nil {
		return nil, err
	}

	storeLog, err := l.svcCtx.StoreLogModel.FindLatestByStoreId(l.ctx, in.StoreId)
	if err != nil {
		return nil, err
	}
	logx.Info("old store agentId: ", storeLog.AgentId)

	store.AgentId = agentId
	storeLog.AgentId = agentId
	logx.Info("new store agentId: ", storeLog.AgentId)
	err = l.svcCtx.StoreLogModel.Update(l.ctx, storeLog)
	if err != nil {
		return nil, err
	}

	err = l.svcCtx.StoreModel.Update(l.ctx, store)
	if err != nil {
		return nil, err
	}

	return &agentClient.EmptyBody{}, nil
}
